﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using KylinORM.Data.Parser.Base;

namespace KylinORM.Data.Parser
{
    /// <summary>
    /// MySql语法解析器
    /// </summary>
    internal class MySqlParser : SqlParserBase
    {
        public MySqlParser(ISqlParserData sqlParserData)
            : base(sqlParserData)
        {
        }

        #region 针对不同数据库Hack
        /// <summary>
        /// 得到表名
        /// </summary>
        /// <param name="entityName"></param>
        /// <returns></returns>
        protected override string GetTableName(string entityName)
        {
            return string.Format("`{0}`", entityName);
        }
        /// <summary>
        /// 将数据库列名用[]包起来
        /// </summary>
        /// <param name="fieldName"></param>
        /// <returns></returns>
        protected override string GetFieldName(string fieldName)
        {
            return string.Format("`{0}`", fieldName);
        }
        /// <summary>
        /// 将参数加上前缀@
        /// </summary>
        /// <param name="fieldName"></param>
        /// <returns></returns>
        protected override string GetParmName(string fieldName)
        {
            return string.Format("?{0}", fieldName);
        }
        #endregion

        #region 拼装SQL
        /// <summary>
        /// 得到插入语句
        /// </summary>
        /// <returns></returns>
        protected override DataQuery GetInsertCondition()
        {
            return new DataQuery
            {
                CommandText = "INSERT INTO {0} ({1}) VALUES ({2});\nSELECT @@IDENTITY AS NewID;"
            };
        }
        /// <summary>
        /// 得到更新语句
        /// </summary>
        /// <returns></returns>
        protected override DataQuery GetUpdateCondition()
        {
            return new DataQuery
            {
                CommandText = "UPDATE {0} SET {1} WHERE {2}"
            };
        }
        /// <summary>
        /// 得到删除语句
        /// </summary>
        /// <returns></returns>
        protected override DataQuery GetDeleteCondition()
        {
            return new DataQuery
            {
                CommandText = "DELETE FROM {0} WHERE {1}"
            };
        }

        /// <summary>
        /// 得到查询语句
        /// </summary>
        /// <returns></returns>
        protected override DataQuery GetSelectCondition()
        {
            return new DataQuery
            {
                CommandText = "SELECT {0} FROM {1} WHERE {2}"
            };
        }
        /// <summary>
        /// 得到指定字段的查询语句
        /// </summary>
        /// <param name="sql">要查询的字段或完整Sql语句</param>
        /// <param name="parms">如果不为null，则替换默认参数</param>
        /// <returns></returns>
        protected override DataQuery GetSelectCondition(string sql, params object[] parms)
        {
            return new DataQuery
            {
                CommandText = "SELECT {0} FROM {1} WHERE {2}"
            };
        }
        /// <summary>
        /// 得到查询语句
        /// </summary>
        /// <param name="skip">跳过N行开始获取</param>
        /// <param name="take">总计获取N行</param>
        /// <returns></returns>
        protected override DataQuery GetSelectCondition(int skip, int take)
        {
            if (skip == 0)
            {
                return new DataQuery
                {
                    CommandText = "SELECT {0} FROM {1} WHERE {2} LIMIT {4}"
                };
            }
            else
            {
                return new DataQuery
                {
                    CommandText = "SELECT {0} FROM {1} WHERE {2} LIMIT {3},{4}"
                };
            }
        }
        /// <summary>
        /// 得到统计语句
        /// </summary>
        /// <returns></returns>
        protected override DataQuery GetCountCondition()
        {
            return new DataQuery
            {
                CommandText = "SELECT COUNT(*) FROM {0} WHERE {1}"
            };
        }
        #endregion

        #region 分页查询
        /// <summary>
        /// 得到分页查询语句
        /// </summary>
        /// <param name="page">页码，从1开始</param>
        /// <param name="itemsPerPage">每页行数</param>
        /// <param name="sql">Sql语句</param>
        /// <param name="args">查询参数</param>
        /// <returns>查询语句,统计语句</returns>
        protected override DataQuery[] GetPageCondition(long page, long itemsPerPage, string sql, params object[] args)
        {
            SqlPagerResult sqlResult = SqlPager.SplitSqlForPaging(sql);
            //分解Sql语句
            if (!sqlResult.Success)
                throw new Exception("无法为Sql语句执行分页查询。");
            //拼装分页查询
            DataQuery query1 = new DataQuery
            {
                CommandText = string.Format("{0}\nLIMIT ?{1},?{2}", sql, args.Length, args.Length + 1),
                Parameters = args.Concat(new object[] { (page - 1) * itemsPerPage, page * itemsPerPage }).ToArray()
            };
            //拼装分页统计
            DataQuery query2 = new DataQuery
            {
                CommandText = sqlResult.SqlCount,
                Parameters = args
            };

            return new DataQuery[] { query1, query2 };
        }
        #endregion

    }
}
